<script>
import { defineComponent, ref, onMounted, computed } from '@vue/composition-api';
import { GetActivityMemberList, ActivityReplaceSign, GetDict, getClassList, addList,GetActivityMemberList1} from '@/api/activity';
import { MessageBox, Message } from 'element-ui';
import { getToken } from '@/utils/auth';
import { userStatusMap } from '../enum';
import router from '@/router';
import { mapGetters } from 'vuex';
import { download } from '@/utils/request';
import Upload from '@/components/StudentUpload/upload';

export default defineComponent({
  props: {
    status: Number,
    activityId: String,
    mark2:Number,
    activityStatus:String,
    createdBy:String
  },
  components: {
    Upload: Upload,
  },
  computed: {
    ...mapGetters(['roles', 'name', 'userName']),
  },
  setup(props) {
    const loading = ref(false);
    const flag = ref(false);
    const open = ref(false);
    const open1 = ref(false);
    const multiple = ref(true);
    const list = ref([]);
    const activityId1 = props.activityId
    const selectionList = ref([]);
    const studentList = ref([]);
    const dictValue = ref([]);
    const classList = ref([]);
    const pageNum = ref(1);
    const uploads = ref();
    const formModel1 = ref({});
    const pageSize = ref(10);
    const total = ref(0);
    const pageNum1 = ref(1);
    const pageSize1 = ref(100);
    const total1 = ref(0);
    const formRef = ref();
    const uploadUrl = ref();
    const uploadHeaders = ref({ Authorization: 'Bearer ' + getToken() });
    const upload = ref(
      {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: '',
      },
    ) 
    const formModel = ref({ studentId: '' });
    const loadData = async () => {
      loading.value = true;
      const payload = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        ...formModel.value,
        status: props.status,
        activityId: props.activityId,
        mark2:props.mark2
      };
      const response = await GetActivityMemberList(payload);
      loading.value = false;
      if (response.code === 200) {
        const { rows, total: rowTotal } = response;
        list.value = rows;
        total.value = rowTotal;
      }
    };

    const replaceSign = (row) => {
      MessageBox.confirm(`是否为 ${row.nickName} 同学代${props.mark2 == '1' ? `签到` : `签退`}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        loading.value = true;
        const response = await ActivityReplaceSign(row.activityMemberId);
        loading.value = false;
        // this.$modal.closeLoading();
        if (response.code === 200) {
          Message({
            message: '操作成功',
            type: 'success',
          });
          refresh();
        } else {
          refresh();
          loading.value = false;
        }
      });
    };
    // 判断是否能查看导入导出按钮
    const canRead =(roles,name) =>{
      var isCanRead = false;
      // console.log(name);
      if (roles) {
        console.log(roles, 'roles');
        for (let i = 0; i < roles.length; i++) {
          if (['admin', 'common'].includes(roles[i])) {
            isCanRead = true;
            break;
          }
          else if (name == props.createdBy) {
            isCanRead = true;
            break;
          }
        }
      }
      console.log(isCanRead, 'isCanRead');
      flag.value = isCanRead;
      return flag;
    }
    const refresh = () => {
      pageNum.value = 1;
      loadData();
    };

    const reset = formEl => {
      formEl.resetFields();
      refresh();
    };
    // 导出
    const exportA = async()=>{
      download(
        '/committee/activityMember/importTemplate',
        {
          
        },
        `activity_${new Date().getTime()}.xlsx`
      );
    };
    const exportActiveStudent1 = async () => {
      download(
        '/committee/activityMember/export',
        {
          activityId:activityId1
        },
        `activity_${new Date().getTime()}.xlsx`
      );
    }
    // 导入
    const exportB = async()=>{
      upload.value.title = '导入信息'
      // upload.value.open = true
      open.value = true
      uploadUrl.value = process.env.VUE_APP_BASE_API + '/committee/activity/importData' + '?updateSupport=' + upload.value.updateSupport + '&activityId=' + props.activityId
      // console.log(uploadUrl.value);
    };

    // 文件上传中处理
    const handleFileUploadProgress = (event, file, fileList)=> {
      upload.value.isUploading = true;
    };
    // 文件上传成功处理
    const handleFileSuccess = (response, file, fileList)=> {
      // upload.value.open = false;
      open.value = false;
      upload.value.isUploading = false;
      uploads.value.clearFiles();
      Message(
          response.msg,
        { dangerouslyUseHTMLString: true }
      );
      setTimeout(() => {
        loadData();
      }, 300);
    };
    // 提交上传文件
    const submitFileForm = async() =>{
      console.log(uploads.value);
      await uploads.value.submit();
    };


    onMounted(() => {
      loadData();
      canRead()
    });
    return {
      submitFileForm,
      exportActiveStudent1,
      handleFileSuccess,
      handleFileUploadProgress,
      canRead,
      exportA,
      uploadUrl,
      open,
      activityId1,
      uploads,
      uploadHeaders,
      exportB,
      flag,
      userStatusMap,
      formRef,
      formModel,
      loadData,
      refresh,
      replaceSign,
      reset,
      loading,
      list,
      total,
      pageNum,
      pageSize,
      upload,
    };
  },
});
</script>

<template>
  <div>
    <el-row>
      <el-form ref="formRef" :model="formModel" inline size="mini">
        <el-form-item label="学生" prop="studentId">
          <el-input v-model="formModel.studentId" placeholder="请输入学号或姓名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="loadData">查询</el-button>
          <el-button type="primary" size="mini" @click="reset(formRef)">重置</el-button>
          <el-button type="primary" size="mini" v-if="mark2 == 0" @click="exportB" v-hasPermi="['education:manager:export']">导入学生</el-button>
          <el-button type="primary" size="mini" v-if="canRead(roles, name) && mark2 == 0"
            @click="exportActiveStudent1">导出</el-button>
          <Upload :activityId="activityId1" @loadData="loadData" v-if="mark2 == 0" v-hasPermi="['education:manager:export']"></Upload>
          <!-- <el-button type="primary" size="mini" v-if="mark2 == 0">颁奖</el-button> -->
          <!-- <el-button type="primary" size="mini" v-if="canRead(roles,name) && mark2 == 0 && ['3','4','5','6','8','9','10','11','12'].includes(activityStatus)" @click="exportA">导出</el-button>
          <el-button type="primary" size="mini" v-if="canRead(roles,name) && mark2 == 0 && ['3','4','5','6','8','9','10','11','12'].includes(activityStatus)" @click="exportB">导入</el-button> -->
          <!-- <el-button type="success" size="mini" @click="refresh">刷新</el-button> -->
        </el-form-item>
      </el-form>
    </el-row>
    <el-row>
      <el-table v-loading="loading" :data="list" border>
        <el-table-column label="学号" align="center" prop="userName" />
        <el-table-column label="姓名" align="center" prop="nickName" />
        <el-table-column label="系部" align="center" prop="unitName" />
        <el-table-column label="学分" align="center" prop="mark"/>
        <el-table-column label="类型" align="center" prop="role">
          <!-- <template slot-scope="scope">
          {{scope.row.audience==1?"观众":scope.row.organizer==1?"组织者":"参与者"}}
          </template> -->
        </el-table-column>
        <el-table-column label="签到时间" align="center" prop="startTime" />
        <el-table-column label="签退时间" align="center" prop="endTime" />
        <el-table-column label="来源" align="center" prop="source">
          <!-- <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="replaceSign(scope.row.studentId, scope.row.sysUser.nickName, name)"
            >
              {{ status == 1 ? '代签到' : '代签退' }}
            </el-button>
          </template> -->
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            {{ userStatusMap.get(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" v-if="mark2 != 0">
         <template slot-scope="scope">
            <el-button
            size="mini"
            type="primary"
            v-hasPermi="['education:manager:qian']"
            @click="replaceSign(scope.row)">
            {{ mark2 == '1' ? '待签到' : '待签退' }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <!-- <template slot-scope="scope">
            {{ userStatusMap.get(scope.row.status) }}
          </template> -->
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="loadData"
      />
    </el-row>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="open" width="400px">
        <el-upload
          ref="uploads"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="uploadHeaders"
          :action="uploadUrl"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="exportA"
              >下载模板</el-link
            >
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>
